<template>
  <div class="profile-container">
    <el-page-header @back="goBack" title="返回" content="个人中心" />
    
    <div class="profile-content">
      <el-row :gutter="20">
        <!-- 左侧用户信息 -->
        <el-col :span="8">
          <el-card class="user-card">
            <template #header>
              <div class="user-header">
                <el-avatar :size="80" :icon="UserFilled"></el-avatar>
                <div class="user-name">
                  <h2>{{ userInfo.username }}</h2>
                  <el-tag v-if="isPro" type="success" effect="dark">PRO会员</el-tag>
                  <el-tag v-else>免费用户</el-tag>
                </div>
              </div>
            </template>
            
            <el-descriptions direction="vertical" :column="1" border>
              <el-descriptions-item label="邮箱地址">{{ userInfo.email }}</el-descriptions-item>
              <el-descriptions-item label="注册时间">{{ formatDate(userInfo.registerDate) }}</el-descriptions-item>
              <el-descriptions-item label="会员状态">
                <span v-if="isPro">Pro会员 (有效期至 {{ formatExpiryDate }})</span>
                <span v-else>免费用户</span>
              </el-descriptions-item>
            </el-descriptions>
            
            <div class="action-buttons">
              <el-button v-if="!isPro" type="primary" @click="upgradeToPro">升级到Pro</el-button>
              <el-button v-else-if="isPro" type="success" @click="renewMembership">续费会员</el-button>
              <el-button @click="openEditDialog">编辑资料</el-button>
            </div>
          </el-card>
        </el-col>
        
        <!-- 右侧使用统计 -->
        <el-col :span="16">
          <el-card class="usage-card">
            <template #header>
              <div class="card-header">
                <h3>功能使用统计</h3>
              </div>
            </template>
            
            <el-tabs>
              <el-tab-pane label="最近使用">
                <div v-if="usageHistory.length > 0">
                  <el-timeline>
                    <el-timeline-item
                      v-for="(item, index) in recentUsageHistory"
                      :key="index"
                      :timestamp="formatDate(item.date)"
                      :type="item.isPro ? 'primary' : 'info'"
                    >
                      {{ item.functionName }}
                    </el-timeline-item>
                  </el-timeline>
                </div>
                <el-empty v-else description="暂无使用记录"></el-empty>
              </el-tab-pane>
              
              <el-tab-pane label="使用统计">
                <div class="usage-stats">
                  <div class="stat-item">
                    <div class="stat-title">总使用次数</div>
                    <div class="stat-value">{{ totalUsage }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-title">免费功能</div>
                    <div class="stat-value">{{ freeUsage }}</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-title">Pro功能</div>
                    <div class="stat-value">{{ proUsage }}</div>
                  </div>
                </div>
                
                <div class="usage-chart">
                  <h4>功能类别使用分布</h4>
                  <!-- 这里可以放图表组件，暂时用简单的进度条代替 -->
                  <div v-for="(category, index) in usageCategories" :key="index" class="category-usage">
                    <div class="category-name">{{ category.name }}</div>
                    <el-progress 
                      :percentage="category.percentage" 
                      :color="category.color"
                      :stroke-width="18"
                      :format="percentageFormat"
                    ></el-progress>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人资料"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="profileForm" label-width="100px" :rules="formRules" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" type="email"></el-input>
        </el-form-item>
        <el-form-item label="修改密码" prop="password">
          <el-input v-model="profileForm.password" type="password" placeholder="不修改请留空"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="profileForm.confirmPassword" type="password" placeholder="不修改请留空"></el-input>
        </el-form-item>
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input v-model="profileForm.currentPassword" type="password" placeholder="不修改请留空"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateProfile">保存</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 升级会员对话框 -->
    <el-dialog
      v-model="upgradeDialogVisible"
      title="升级到Pro会员"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="upgrade-content">
        <div class="upgrade-header">
          <h2>柯基工具箱 Pro会员</h2>
          <div class="price">¥5 <span class="price-unit">/ 月</span></div>
        </div>
        
        <div class="benefits">
          <h3>Pro会员特权</h3>
          <ul>
            <li><el-icon><Check /></el-icon> 高级格式转换功能</li>
            <li><el-icon><Check /></el-icon> OCR文字识别功能</li>
            <li><el-icon><Check /></el-icon> PDF高级操作</li>
            <li><el-icon><Check /></el-icon> AI辅助生成功能</li>
            <li><el-icon><Check /></el-icon> 无广告体验</li>
            <li><el-icon><Check /></el-icon> 10GB云存储空间</li>
          </ul>
        </div>
        
        <div class="payment-actions">
          <el-button type="success" size="large" :loading="upgrading" @click="processUpgrade">立即升级</el-button>
          <el-button @click="upgradeDialogVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
/**
 * 用户个人资料页面组件
 * 显示用户信息、会员状态和使用统计
 */
import { ref, computed, reactive, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { UserFilled, Check } from '@element-plus/icons-vue';
// 导入API服务
import { UserService } from '../../services';

const store = useStore();
const router = useRouter();
const loading = ref(false);
const isUpdating = ref(false);

// 获取用户信息
const userInfo = ref({
  username: '',
  email: '',
  registerDate: '',
  isPro: false,
  proExpiryDate: null
});

const getUserInfo = async () => {
  loading.value = true;
  try {
    // 首先尝试从本地store获取用户信息
    const storeUser = store.state.user;
    if (storeUser) {
      userInfo.value = {
        ...userInfo.value,
        ...storeUser
      };
    }
    
    // 然后尝试从API获取最新用户信息
    const response = await UserService.getUserProfile();
    if (response && response.data) {
      userInfo.value = response.data;
      // 更新store中的用户信息
      store.commit('updateUserProfile', response.data);
    }
  } catch (error) {
    console.error('获取用户信息失败', error);
    // 如果API请求失败但store中有用户信息，继续使用store中的信息
    if (!userInfo.value.username && store.state.user) {
      userInfo.value = {
        ...userInfo.value,
        ...store.state.user
      };
    } else if (!userInfo.value.username) {
      // 如果没有任何用户信息，则跳转到登录页
      ElMessage.error('获取用户信息失败，请重新登录');
      router.push('/login');
    }
  } finally {
    loading.value = false;
  }
};

// 格式化日期的函数
const formatDate = (dateString) => {
  if (!dateString) return '未知';
  try {
    return new Date(dateString).toLocaleDateString('zh-CN');
  } catch (e) {
    return dateString || '未知';
  }
};

// 用户是否为Pro会员
const isPro = computed(() => userInfo.value?.isPro || false);

// 会员到期日期格式化
const formatExpiryDate = computed(() => {
  if (!userInfo.value?.proExpiryDate) return '未开通';
  return new Date(userInfo.value.proExpiryDate).toLocaleDateString('zh-CN');
});

// 使用统计计算属性
const usageHistory = computed(() => store.state.usageHistory || []);
const recentUsageHistory = computed(() => {
  return [...usageHistory.value].sort((a, b) => new Date(b.date) - new Date(a.date)).slice(0, 5);
});
const totalUsage = computed(() => usageHistory.value.length);
const freeUsage = computed(() => usageHistory.value.filter(item => !item.isPro).length);
const proUsage = computed(() => usageHistory.value.filter(item => item.isPro).length);

// 分类使用统计（模拟数据）
const usageCategories = ref([
  { name: '文本工具', percentage: 35, color: '#409EFF' },
  { name: '图像工具', percentage: 25, color: '#67C23A' },
  { name: '格式转换', percentage: 20, color: '#E6A23C' },
  { name: '效率工具', percentage: 15, color: '#F56C6C' },
  { name: '数据工具', percentage: 5, color: '#909399' }
]);

const percentageFormat = (percentage) => {
  return `${percentage}%`;
};

// 编辑资料相关
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const profileForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  currentPassword: ''
});

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (profileForm.password && value !== profileForm.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 同步表单数据
const syncFormData = () => {
  if (userInfo.value) {
    profileForm.username = userInfo.value.username || '';
    profileForm.email = userInfo.value.email || '';
  }
};

// 更新个人资料
const updateProfile = async () => {
  if (profileForm.password && profileForm.password !== profileForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致');
    return;
  }
  
  if (profileForm.password && !profileForm.currentPassword) {
    ElMessage.error('修改密码需要输入当前密码');
    return;
  }
  
  isUpdating.value = true;
  
  try {
    const updateData = {
      email: profileForm.email
    };
    
    // 如果修改了密码，加入密码相关字段
    if (profileForm.password) {
      updateData.password = profileForm.password;
      updateData.currentPassword = profileForm.currentPassword;
    }
    
    const response = await UserService.updateUserProfile(updateData);
    
    // 更新本地用户信息
    userInfo.value = response.data;
    store.commit('updateUserProfile', response.data);
    
    // 清空密码字段
    profileForm.password = '';
    profileForm.confirmPassword = '';
    profileForm.currentPassword = '';
    
    ElMessage.success('个人资料更新成功');
  } catch (error) {
    if (error.response && error.response.status === 401) {
      ElMessage.error('当前密码错误');
    } else {
      ElMessage.error(error.message || '更新个人资料失败');
    }
  } finally {
    isUpdating.value = false;
  }
};

// 打开编辑对话框
const openEditDialog = () => {
  editDialogVisible.value = true;
};

// 会员升级相关
const upgradeDialogVisible = ref(false);
const upgrading = ref(false);

const upgradeToPro = () => {
  upgradeDialogVisible.value = true;
};

const renewMembership = () => {
  upgradeDialogVisible.value = true;
};

const processUpgrade = async () => {
  upgrading.value = true;
  
  try {
    await store.dispatch('upgradeMembership');
    ElMessage.success('恭喜您，已成功升级为Pro会员！');
    upgradeDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('升级失败，请稍后再试');
  } finally {
    upgrading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 组件挂载时获取用户信息
onMounted(async () => {
  await getUserInfo();
  syncFormData();
});
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-content {
  margin-top: 20px;
}

.user-card,
.usage-card {
  margin-bottom: 20px;
  height: 100%;
}

.user-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.user-name {
  margin-top: 15px;
  text-align: center;
}

.user-name h2 {
  margin: 0 0 10px 0;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.usage-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  border-radius: 4px;
  background-color: #f5f7fa;
  flex: 1;
  margin: 0 5px;
}

.stat-title {
  font-size: 14px;
  color: var(--dark-gray);
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--primary-dark);
}

.usage-chart {
  margin-top: 20px;
}

.usage-chart h4 {
  margin-bottom: 15px;
}

.category-usage {
  margin-bottom: 15px;
}

.category-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.upgrade-content {
  padding: 0 20px;
}

.upgrade-header {
  text-align: center;
  margin-bottom: 30px;
}

.upgrade-header h2 {
  color: var(--primary-dark);
  margin-bottom: 10px;
}

.price {
  font-size: 36px;
  color: var(--secondary-color);
  font-weight: bold;
}

.price-unit {
  font-size: 16px;
  color: var(--dark-gray);
  font-weight: normal;
}

.benefits {
  margin-bottom: 30px;
}

.benefits h3 {
  color: var(--primary-dark);
  margin-bottom: 15px;
}

.benefits ul {
  list-style: none;
  padding: 0;
}

.benefits li {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
  color: var(--black);
}

.benefits li .el-icon {
  color: var(--secondary-color);
}

.payment-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}
</style> 